<template>
  <div>
    <div style="height: 50px;overflow: auto;"><button @click="downloadImage()">下载图片</button></div>
    <div id="chartBox" ref="chart" style="width:12500px;height:calc(100vh - 236px);" />

  </div>
  <!-- <div><button onclick="downloadImage()">下载图片</button></div> -->
</template>

<script>
import * as echarts from 'echarts'
import { DataList } from '@/utils/authority11.js'
export default {
  name: 'TreeChart',
  data() {
    return {
      data: [],
      DataList: DataList, // 树结构数据
      myChart: null,
      option: {}

    }
  },
  created() {
    // 转换数据
    this.data = this.eachReplaceKey(this.DataList)
  },
  mounted() {
    this.drawChart()
  },
  methods: {
    // 处理数据
    eachReplaceKey(data) {
      const item = []
      data.map((list) => {
        const newData = {}
        newData.id = list.id
        newData.name = list.institutionName //
        newData.children = list.dson
        newData.value = list.peopleNumber
        newData.institutionGrade = list.institutionGrade // 机构等级
        newData.institutionNumber = list.institutionNumber // 机构编码"
        newData.administrationRank = list.administrationRank // 行政级另"
        newData.institutionFather = list.institutionFatherName // 上级机构"
        newData.xzPeople = list.xzPeople // 行政负责"
        newData.dwPeople = list.dwPeople // 党务负责"
        newData.institutionPlace = list.institutionPlace // 办必地址"
        newData.phone = list.phone // 电话号码"
        newData.remark = list.remark // 部门职责"
        newData.classification = list.classification // 行政级别
        newData.type = list.type // 1撤销 2合并"
        newData.takeEffectData = list.takeEffectData // 牛效日期"
        newData.ratifyData = list.ratifyData // 批准日期"
        newData.documentumber = list.documentumber // 文号"
        newData.settingNumber = list.settingNumber // 单位"
        newData.mergeMechanism = list.mergeMechanism // 撤销就是当前机构的名，合并就是需要合并的机构名，逗号分隔
        newData.mergeMechanismId = list.mergeMechanismId // 撤销就是当前机构的id，合并就是需要合并的机构id，逗号分限
        newData.maxNumber = list.maxNumber // 编制人数
        newData.organizationNum = list.organizationNum
        if (list.dson != null) {
          newData.children = this.eachReplaceKey(list.dson)
        }
        if (newData.institutionGrade == '1') {
          newData.itemStyle = {
            color: '#CCE5FF', //
            borderColor: '#DCDFE6'
          }
        }
        if (list.dson != null) {
          newData.children = this.eachReplaceKey(list.dson)
          newData.children.forEach(item => {
            if (item.institutionGrade == '2') {
              item.itemStyle = {
                color: '#EDF6FF',
                borderColor: '#DCDFE6'
              }
            }
            if (item.institutionGrade == '3') {
              item.itemStyle = {
                color: '#FFFFFF',
                borderColor: '#DCDFE6'
              }
            }
            // 除了第一、二级，其他级别的样式展示
            // else{
            //     item.itemStyle={
            //         color:'#FFFFFF',
            //         borderColor:'#DCDFE6',
            //     }
            // }
          })
        }
        item.push(newData)
      })
      return item
    },
    drawChart() {
      // 初始化图表
      this.myChart = echarts.init(this.$refs.chart)
      this.myChart.showLoading()
      var echartNowData = [] // 当前鼠标所在的节点数据
      // 指定图表的配置项和数据
      this.option = {
        backgroundColor: 'rgba(26, 107, 232, 0.047058823529411764)',
        calculable: false,
        tooltip: {
          trigger: 'item', // item
          triggerOn: 'mousemove', // click  mousemove
          backgroundColor: 'unset',
          position: 'right', //
          renderMode: 'html',
          confine: true, // 将tooltip限制在图表区域内
          enterable: true, // 鼠标可以进入提示框
          padding: 0,
          // left: -18,
          textStyle: {
            color: 'white' // 设置 tooltip
          },
          formatter: function(params) {
            echartNowData = params.data
            const nameData = {
              name: ''
            }
            //  position: relative;right: 120px;  padding: 26px;
            if (params.data.classification === 24) nameData.name = '机构名称'
            if (params.data.classification === 25) nameData.name = '部门名称'
            if (params.data.classification === 26) nameData.name = '科室名称'
            //  <div style="position: absolute;left: -20px;top:50%;transform:translateY(-50%);float: left;display:flex;justify-content: space-between; flex-direction: column;align-items:flex-end">
            //   <span onclick="handleNew()" style="pointer-events: auto;display:block;width:29px;height:29px;border-radius: 50%;margin-bottom: 5px;background: #1AA094;text-align:center;font-size: 18px;padding-top: 5px;" class="el-icon-plus"></span>
            //   <span onclick="handleEdit()" style="pointer-events: auto;display:block;width:29px;height:29px;border-radius: 50%;margin-bottom: 5px;background: #1AA094;text-align:center;font-size: 18px;padding-top: 5px;" class="el-icon-edit-outline"></span>
            //   <span onclick="handleDelete()" style="pointer-events: auto;display:block;width:29px;height:29px;border-radius: 50%;background: #1AA094;text-align:center;font-size: 18px;padding-top: 5px;" class="el-icon-delete"></span>
            //   </div>
            const html = `<div style="position: absolute;left: -20px;top:50%;transform:translateY(-50%);float: left;display:flex;justify-content: space-between; flex-direction: column;align-items:flex-end">
                <span onclick="handleNew()" style="pointer-events: auto;display:block;width:29px;height:29px;border-radius: 50%;margin-bottom: 5px;background: #1AA094;text-align:center;font-size: 18px;padding-top: 5px;" class="el-icon-plus"></span>
                <span onclick="handleEdit()" style="pointer-events: auto;display:block;width:29px;height:29px;border-radius: 50%;margin-bottom: 5px;background: #1AA094;text-align:center;font-size: 18px;padding-top: 5px;" class="el-icon-edit-outline"></span>
                <span onclick="handleDelete()" style="pointer-events: auto;display:block;width:29px;height:29px;border-radius: 50%;background: #1AA094;text-align:center;font-size: 18px;padding-top: 5px;" class="el-icon-delete"></span>
              </div>
              <div style="background:white;border-radius: 7px;color: #666; display: flex;justify-content: space-between; padding:5px 15px;">
                
                <div>
                   <p style="margin:10px 0">编码：</p>
                  <p style="margin:10px 0">${nameData.name}：</p>
                  <p style="margin:10px 0">行政级别：</p>
                  <p style="margin:10px 0">机构等级：</p>
                  <p style="margin:10px 0">上级机构：</p>
                  <p style="margin:10px 0">行政负责人：</p>
                  <p style="margin:10px 0">行政负责人号码：</p>
                  <p style="margin:10px 0">党务负责人：</p>
                  <p style="margin:10px 0">办公地址：</p>
                  <p style="margin:10px 0">定编人数: </p>
                  <p style="margin:10px 0">在编人数：</p>
                  <p style="margin:10px 0">在岗人数：</p>
                </div>
                <div style="text-align: right">
                   <p>${params.data.institutionNumber || '-'}</p>
                  <p>${params.data.name || '-'}</p>
                  <p>${params.data.administrationRank || '-'}</p>
                  <p>${params.data.institutionGrade || '-'}级</p>
                  <p>${params.data.institutionFather || '-'}</p>
                  <p>${params.data.xzPeople || '-'}</p>
                  <p>${params.data.phone || '-'}</p>
                  <p>${params.data.dwPeople || '-'}</p>
                  <p>${params.data.institutionPlace || '-'}</p>
                  <p>${params.data.maxNumber || '-'}人</p>
                  <p>${params.data.settingNumber || '-'}人</p>
                  <p>${params.data.maxNumber || '-'}人</p>
                </div>
              </div>`
            return html
          }
        },
        toolbox: {
          show: true,
          feature: {
            dataZoom: {
              show: true
            },
            saveAsImage: {
              show: true
            }

          }
        },
        series: [
          {
            name: '树图',
            type: 'tree',
            orient: 'vertical', // vertical horizontal
            rootLocation: { x: '50%', y: '15%' }, // 根节点位置  {x: 'center',y: 10}
            hoverAnimation: false,
            nodePadding: 8,
            layerPadding: 30,
            // symbol: 'rectangle',
            borderColor: 'black',
            symbolSize: [140, 100],
            symbol: 'rect',
            symbolKeepAspect: true,
            edgeShape: 'polyline',
            roam: true,
            initialTreeDepth: -1,
            left: '0%',
            width: 12500,
            expandAndCollapse: false,

            itemStyle: {
              normal: {
                // color: 'rgba(255, 255, 255, 1)', // 节点背景色
                'borderWidth': 1,
                'borderColor': '#b2d8d4',
                label: {
                  show: true,
                  position: 'inside',
                  // backgroundColor: 'rgba(255, 255, 255, 1)',
                  lineHeight: 30,
                  textStyle: {
                    color: '##30313',
                    fontSize: 14
                    // fontWeight:  'bolder'
                  },
                  formatter: function(params) {
                    var text = params.data.name.toString()
                    var tt = `${text.length > 8 ? text.substring(0, 8) : text}${text.length > 10 ? '...' : ''}`
                    return `{a|${tt}}` + '\n' + `{b|在编人数:${params.data.settingNumber}}` + '\n' + `{b|在岗人数:${params.data.maxNumber}}`
                    // return tt + '\n在编人数:' + params.data.settingNumber + '\n在岗人数:' + params.data.maxNumber
                  },
                  rich: {
                    a: {
                      color: '#303133', // 自定义样式a
                      fontWeight: 'bold',
                      fontSize: 14,
                      padding: [5, 0, 5, 0],
                      align: 'center'
                    },
                    b: {
                      color: '#909399', // 自定义样式b
                      fontSize: 12,
                      align: 'center'
                    }
                  }
                },
                lineStyle: {
                  color: '#CCE5FF',
                  width: 1
                }
              },
              emphasis: {
                // 鼠标悬停时的样式
                borderColor: '#409EFF', // #42b983
                borderWidth: '2',
                color: '#CCE5FF'
              }

            },

            data: this.data
          }
        ]
      }

      // 使用刚指定的配置项和数据显示图表。
      this.myChart.setOption(this.option)
      this.myChart.hideLoading()

      window.handleNew = function() {
        // 新增的逻辑
        console.log(echartNowData)
        console.log('新增按钮被点击')
      }
      // // 编辑按钮点击事件
      window.handleEdit = function() {
        // 编辑的逻辑
        console.log('编辑按钮被点击')
        console.log(echartNowData)
      }

      // // 删除按钮点击事件
      window.handleDelete = function() {
        // 删除的逻辑
        console.log('删除按钮被点击')
        console.log(echartNowData)
      }
    },

    // 下载图片
    downloadImage1() {
      // 获取图表的 Base64 URL
      var base64URL = this.myChart.getDataURL({
        type: 'jpeg', // 或者 'jpeg'
        pixelRatio: 2, // 导出的图片分辨率比例
        backgroundColor: 'white' // 导出的图片背景色，默认使用 option 里的 backgroundColor
      })

      // 创建一个 Blob 对象，用于保存图片的二进制数据
      var blob = this.dataURLtoBlob(base64URL)

      // 创建一个隐藏的 a 标签用于下载
      var a = document.createElement('a')
      a.href = URL.createObjectURL(blob)
      a.download = 'echart.png' // 设置下载文件的名称
      a.style.display = 'none'

      // 触发 a 标签的 click 事件开始下载
      document.body.appendChild(a)
      a.click()

      // 之后可以移除 a 标签
      document.body.removeChild(a)
    },

    // 将 Base64 URL 转换为 Blob 对象
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(','); var mime = arr[0].match(/:(.*?);/)[1]
      var bstr = atob(arr[1]); var n = bstr.length; var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },

    // 下载图片
    downloadImage() {
      this.downloadCanvasAsImage(null, 'chartBox', 'zzjg.png')
    },
    downloadCanvasAsImage(link, canvasId, filename) {
      var chartBox = document.getElementById('chartBox')
      if (chartBox) {
        var firstDiv = chartBox.children[0]
        if (firstDiv && firstDiv.tagName.toLowerCase() === 'div') {
          var canvas = firstDiv.children[0]
          if (canvas && canvas.tagName.toLowerCase() === 'canvas') {
            // 对canvas进行操作
            console.log(canvas)
            var imageUrl = canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream')
            // var linkElement = document.createElement('a');
            // linkElement.setAttribute('href', imageUrl);
            // linkElement.setAttribute('download', filename);
            // linkElement.click();
            var img = document.createElement('img')
            img.src = imageUrl
            img.width = canvas.width
            img.height = canvas.height

            // 新标签页中显示图片
            var newTab = window.open('', '_blank')
            newTab.document.write('<img src="' + img.src + '" alt="Canvas Image" />')
          }
        }
      }
    }

  }
}
</script>

<style scoped>
/* 你可以在这里添加一些样式 */

</style>

